package cn.cqs.shiro;

import cn.cqs.Entity.User;
import cn.cqs.serivce.Userservice;
import constants.SlatPool;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {


    @Autowired
    PasswordService passwordService;
    @Autowired
    Userservice userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        String username = "liu"; //用户名及salt1
//        String password = "202cb962ac59075b964b07152d234b70"; //加密后的密码
//        String password= passwordService.encryptPassword("123");
//        String salt2 = "202cb962ac59075b964b07152d234b70";
//        认证信息SimpleAuthenticationInfo
//        SimpleAuthenticationInfo ai = new SimpleAuthenticationInfo(username, password, getName());
//        ai.setCredentialsSalt(ByteSource.Util.bytes(username+salt2)); //盐是用户名+随机数
//        return ai;

        String username= (String) token.getPrincipal();
//        根据tokent用户名查找是存在
        User user = userService.findByUsername(username);
        if(user ==null){
            throw new UnknownAccountException();//没找到帐号
        }
        if(Boolean.TRUE.equals(user.getLocked())){
            throw new LockedAccountException(); //帐号锁定
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),
                ByteSource.Util.bytes(SlatPool.SLAT)  , getName());
        return authenticationInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
